import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  queryProduceQuestionChoiceList,
  deleteProduceQuestionChoice,
  addOrUpdateProduceQuestionChoice
} from "@/api/exam";
import { addDialog, closeDialog } from "@/components/ReDialog";
import { type FormItemProps } from "./types";
import { ref, onMounted, computed, h } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";

export function useRole() {
  const router = useRouter();
  const { query } = useRoute();

  const hideVal = ref(false);
  const questionIdVal = ref(query?.id ?? "");
  const typeRef = ref(-1);
  const ftitleRef = ref();
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const columns: TableColumnList = [
    {
      label: "序号",
      minWidth: 30,
      type: "index",
      index: (index: number) => {
        return index + 1;
      },
      hide: () => hideVal.value
    },
    {
      label: "选项",
      prop: "name",
      minWidth: 40
    },
    {
      label: "内容",
      prop: "content",
      minWidth: 150,
      align: "left",
      cellRenderer: ({ row }) => (
        <el-popover effect="light" trigger="hover" placement="left" width="300">
          {{
            default: () => {
              return (
                <>
                  <el-card>
                    <div v-html={row.content} />
                  </el-card>
                </>
              );
            },
            reference: () => {
              // 去掉 HTML标签
              let result = row.content.replace(/(<([^>]+)>)/gi, "");
              //end
              const size = result.length;
              if (size > 40) {
                result = result.slice(0, 40) + "...";
              }
              return <div v-html={result} />;
            }
          }}
        </el-popover>
      )
    },
    {
      label: "创建时间",
      prop: "addtime",
      minWidth: 80,
      hide: () => hideVal.value
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  function handleDelete(row) {
    deleteProduceQuestionChoice(row)
      .then(res => {
        if (res.success) {
          message(`您删除了选项选项为"${row.name}"的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message("删除数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("删除数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    queryProduceQuestionChoiceList({
      questionid: questionIdVal.value, //关联题库ID
      pageSize: 20
    })
      .then(res => {
        if (res.success) {
          dataList.value = res.data.list;
          ftitleRef.value = res.data.title;
          typeRef.value = res.data.type;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    if (!questionIdVal.value) {
      message("进入页面异常，请关闭后再试!", { type: "error" });
      closePageTag();
      return;
    }
    addDialog({
      title: `${title}选项`,
      props: {
        formInline: {
          id: row?.id ?? "",
          questionid: row?.questionid ?? questionIdVal.value,
          name: row?.name ?? "",
          content: row?.content ?? "",
          addtime: row?.addtime ?? "",
          updatetime: row?.updatetime ?? ""
        }
      },
      width: "60%",
      draggable: true,
      fullscreen: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      footerButtons: [
        {
          label: "取消",
          type: "info",
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index);
          }
        },
        {
          label: "确定",
          type: "success",
          btnClick: ({ dialog: { options, index } }) => {
            const FormRef = formRef.value.getRef();
            const curData = options.props.formInline as FormItemProps;
            function chores() {
              message(`您${title}了选项名称为"${curData.name}"的这条数据`, {
                type: "success"
              });
              closeDialog(options, index); // 关闭弹框
              onSearch(); // 刷新表格数据
            }
            FormRef.validate(valid => {
              if (valid) {
                addOrUpdateProduceQuestionChoice(curData)
                  .then(res => {
                    if (res.success) {
                      chores();
                    } else {
                      message("提交失败:" + res.errMsg, { type: "error" });
                    }
                  })
                  .catch(error => {
                    message("提交失败:" + JSON.stringify(error), {
                      type: "error"
                    });
                  });
              }
            });
          }
        }
      ]
    });
  }

  const multiTags = computed(() => {
    return useMultiTagsStoreHook()?.multiTags;
  });

  function closePageTag() {
    useMultiTagsStoreHook().handleTags("splice", "/question/simulator/choice");
    router.push({
      path: multiTags.value[(multiTags as any).value.length - 1].path
    });
  }

  onMounted(() => {
    if (questionIdVal.value) {
      onSearch();
    } else {
      message("进入页面异常，请关闭后再试!", { type: "error" });
      closePageTag();
    }
  });

  return {
    closePageTag,
    loading,
    columns,
    dataList,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    router,
    ftitleRef,
    typeRef,
    hideVal,
    questionIdVal
  };
}
